package com.m3u8;

import android.util.Log;

import com.m3u8.db.model.TsModel;
import com.m3u8.http.OKhttper;
import com.m3u8.pool.ObjectPool;
import com.m3u8.pool.ObjectPoolItem;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;

/**
 * 下载ts的线程
 */
public class DownloadTask implements Runnable {

    private WeakReference<OnDownloadTsListener> weakReference;
    private List<TsModel> tss;
    private long m3u8Id;
    private String m3u8Url;
    private boolean isTsPause = false;

    public DownloadTask(long m3u8Id, String m3u8Url, List<TsModel> tss) {
        this.m3u8Id = m3u8Id;
        this.m3u8Url = m3u8Url;
        this.tss = tss;
    }

    public void setDownloadListener(OnDownloadTsListener downloadListener) {
        this.weakReference = new WeakReference<>(downloadListener);
    }

    public void setTsPause(boolean isTsPause) {
        this.isTsPause = isTsPause;
    }

    @Override
    public void run() {
        if (!tss.isEmpty()) {
            TsModel ts;
            int i = 0;
            while (!isTsPause && i < tss.size()) {
                ts = tss.get(i);
                if (weakReference.get() != null) {
                    weakReference.get().onTsStart(ts.getId(), ts.getTsUrl());
                }
                File tsFile = new File(ts.getLocalPath());
                Response response = null;
                BufferedSource source = null;
                BufferedSink sink = null;
                try {
                    if (!tsFile.exists()) {
                        tsFile.createNewFile();
                    } else {
                        tsFile.delete();
                        tsFile.createNewFile();
                    }
                    Log.d("ttt", "download ts---" + ts.getTsUrl());
                    OkHttpClient okHttpClient = OKhttper.getOkhttpClient();
                    Request request = new Request.Builder().url(ts.getTsUrl()).build();
                    response = okHttpClient.newCall(request).execute();
                    if (response != null && response.isSuccessful()) {
                        ResponseBody body = response.body();
                        if (body != null) {
                            source = body.source();
                            sink = Okio.buffer(Okio.sink(tsFile));
                            Buffer buffer = sink.getBuffer();
                            int bufferSize = 200 * 1024; //200kb
                            while (source.read(buffer, bufferSize) != -1) {
                                sink.emit();
                            }
                        }
                        if (weakReference.get() != null) {
                            weakReference.get().onTsComplete(ts.getId());
                        }
                        if (weakReference.get() != null) {
                            weakReference.get().onProcess(m3u8Id, m3u8Url, ts.getTsUrl());
                        }
                    }
                } catch (Exception e) {
                    if (weakReference.get() != null) {
                        weakReference.get().onTsError(ts.getId(), ts.getTsUrl());
                    }
                } finally {
                    if (response != null) {
                        response.close();
                    }
                    if (source != null) {
                        try {
                            source.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (sink != null) {
                        try {
                            sink.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                i++;
            }
            if (weakReference.get() != null) {
                weakReference.get().onTaskComplete(m3u8Id, this);
            }
            //recycle();
        }
    }

    /**
     * 对象池重用
     *
     * @param m3u8Id
     * @param m3u8Url
     * @param tss
     * @return
     */
//    public static DownloadTask obtain(long m3u8Id, String m3u8Url, List<TsModel> tss) {
//        DownloadTask task = ObjectPool.obtain(DownloadTask.class);
//        if (task == null) {
//            task = new DownloadTask();
//        }
//        Log.d("ttt0", "obtain" + task.toString());
//        task.m3u8Id = m3u8Id;
//        task.m3u8Url = m3u8Url;
//        task.tss = tss;
//        return task;
//    }

//    @Override
//    public void recycle() {
//        Log.d("ttt0", "recycle" + this.toString());
//        m3u8Id = 0;
//        m3u8Url = null;
//        tss = null;
//        ObjectPool.recycle(this);
//    }
}
